//
//  HMComposeViewController.swift
//  iOSWeibo12
//
//  Created by Admin on 16/9/12.
//  Copyright © 2016年 itcast. All rights reserved.
//

import UIKit
import SVProgressHUD

class HMComposeViewController: UIViewController {

    @IBOutlet weak var textView: UITextView!
    
    @IBOutlet weak var toolBar: UIToolbar!
    @IBOutlet weak var toolBarBottomCons: NSLayoutConstraint!
    // 微博文本长度
    @IBOutlet weak var lengthTipLabel: UILabel!
    
    /// 照片选择器视图底部约束
    private var photoSelectorViewBottomCons: NSLayoutConstraint?
    
    /// 微博文本最大长度
    let statusMaxLength = 20
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // 添加键盘frame改变的通知
        NotificationCenter.default.addObserver(self, selector: #selector(willChangeFrame(notification:)), name: NSNotification.Name.UIKeyboardWillChangeFrame, object: nil)
        
        textView.delegate = self

        setNavigationBar()
        setToolBar()
        setupTipLabel()
        setupPhotoSelectorView()
    }
    
    // view已经显示
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        
        if photoSelectorViewBottomCons?.constant != 0 {
            // 主动弹出键盘
            textView.becomeFirstResponder()
        }
    }
    
    deinit {
        // 移除通知监听
        NotificationCenter.default.removeObserver(self)
    }
    
    /// 键盘改变调用这个通知方法
    func willChangeFrame(notification: NSNotification) -> Void {
        // 获取键盘最终的frame
        let endFrameObject = notification.userInfo![UIKeyboardFrameEndUserInfoKey]! as AnyObject
        
        let endFrame = endFrameObject.cgRectValue!
        
        // toolBar底部到父控件的底部的距离 = 屏幕高度 - 键盘.frame.origin.y
        toolBarBottomCons.constant = UIScreen.height - endFrame.origin.y
        
        // 获取动画时间
        let durationAnyObject = notification.userInfo![UIKeyboardAnimationDurationUserInfoKey]! as AnyObject
        let duration = durationAnyObject.doubleValue!
        
        // toolBar动画
        UIView.animate(withDuration: duration) {
            self.view.layoutIfNeeded()
        }
    }
    
    private func setupPhotoSelectorView() {
        let photoSelectorView: UIView = photoSelectorVC.view
        self.view.insertSubview(photoSelectorView, belowSubview: toolBar)
        self.addChildViewController(photoSelectorVC)
        
        // 设置约束
        photoSelectorView.translatesAutoresizingMaskIntoConstraints = false
        let viewDict = ["psv" : photoSelectorView]
        
        // 左右和父控件重合
        view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-0-[psv]-0-|", options: [], metrics: nil, views: viewDict))
        
        // 底部和父控件底部重合
        let height = UIScreen.height * 0.6
        photoSelectorViewBottomCons = NSLayoutConstraint(item: photoSelectorView, attribute: .bottom, relatedBy: .equal, toItem: self.view, attribute: .bottom, multiplier: 1, constant: height)
        view.addConstraint(photoSelectorViewBottomCons!)
        
        // 高度等于父控件高度0.6
        view.addConstraint(NSLayoutConstraint(item: photoSelectorView, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: height))
    }
    
    /// 设置长度label
    private func setupTipLabel() {
        lengthTipLabel.text = "\(statusMaxLength)"
    }
    
    /// 设置toolBar
    private func setToolBar() {
        // 创建toolBar上的item
        var items = [UIBarButtonItem]()
        
        // 每个item对应的图片名称
        let itemSettings = [["imageName": "compose_toolbar_picture", "action": "picture"],
                            ["imageName": "compose_trendbutton_background", "action": "trend"],
                            ["imageName": "compose_mentionbutton_background", "action": "mention"],
                            ["imageName": "compose_emoticonbutton_background", "action": "emoticon:"],
                            ["imageName": "compose_add_background", "action": "add"]]
        
        // 遍历 itemSettings 创建 UIBarbuttonItem
        for (index, dict) in itemSettings.enumerated() {
            // 获取图片名称
            let imageName = dict["imageName"]!
            let highlightImageName = imageName + "_highlighted"
            let action = dict["action"]!
            
            let button = UIButton()
            button.setImage(UIImage(named: imageName), for: .normal)
            button.setImage(UIImage(named: highlightImageName), for: .highlighted)
            button.sizeToFit()
            
            // 按钮添加tag
            button.tag = index
            // 按钮添加点击事件
            button.addTarget(self, action: Selector(action), for: UIControlEvents.touchUpInside)
            
            // 追加按钮
            let barButtonItem = UIBarButtonItem(customView: button)
            items.append(barButtonItem)
            
            // 添加弹簧
            items.append(UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.flexibleSpace, target: nil, action: nil))
        }
        // 删除最后一根弹簧
        items.removeLast()
        
        // 将barButtonItems赋值给toolBar
        toolBar.items = items
    }
    
    // MARK: - toolBar item 点击事件
    func picture() {
        // 显示 照片选择器
        self.photoSelectorViewBottomCons?.constant = 0
        
        // 隐藏键盘
        textView.resignFirstResponder()
        
        UIView.animate(withDuration: 0.25) { () -> Void in
            self.view.layoutIfNeeded()
        }
    }
    
    func trend() {
        print("#")
    }
    
    func mention() {
        print("@")
    }
    
    func emoticon(_ button: UIButton) {
        print("表情 = \(button)")
        
        // 设置textView.inputView并不会立马改变键盘,在下次弹出的时候才会改变
        textView.resignFirstResponder()
        
        // 如果是系统键盘就切换到自定义的键盘,如果是自定义的键盘就切换到系统键盘
        textView.inputView = textView.inputView == nil ? emoticonKeyboard : nil
        
        let image: UIImage
        let highlightedImage: UIImage
        if textView.inputView == nil {
            image = UIImage(named: "compose_emoticonbutton_background")!
            highlightedImage = UIImage(named: "compose_emoticonbutton_background_highlighted")!
        } else {
            image = UIImage(named: "compose_keyboardbutton_background")!
            highlightedImage = UIImage(named: "compose_keyboardbutton_background_highlighted")!
        }
        
        // 设置按钮图片
        button.setImage(image, for: .normal)
        button.setImage(highlightedImage, for: .highlighted)
        
        // 延迟0.25秒将键盘弹出来
        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.25) {
            self.textView.becomeFirstResponder()
        }
    }
    
    func add() {
        print("加号")
    }
    
    func itemClick(button: UIButton) -> Void {
        print("button: \(button.tag)")
        switch button.tag {
        case 0:
            print("图片")
        case 1:
            print("#")
        case 2:
            print("@")
        case 3:
            print("表情")
        case 4:
            print("加号")
        default:
            print("没有按钮")
        }
    }
    
    /// 设置导航栏
    private func setNavigationBar() {
        // 导航栏左边按钮
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.plain, target: self, action: #selector(close))
        
        // 导航栏右边按钮
        navigationItem.rightBarButtonItem = UIBarButtonItem(customView: sendButton)
        // 发布按钮一开始不可用
        sendButton.isEnabled = false
        
        setNavTitle()
    }
    
    /// 设置导航栏标题
    private func setNavTitle() {
        // 前缀
        let prefix = "发微博"
        
        // 判断是否有用户名称.
        if let name = HMUserAccountViewModel.shared.userAccount?.screen_name {
            // 有用户名称,拼接用户名称. \n 表示换行
            let titleText = prefix + "\n" + name
            
            // 创建label
            let label = UILabel()
            
            // 显示多行
            label.numberOfLines = 0
            // 默认左对齐,改成居中对齐
            label.textAlignment = NSTextAlignment.center
            
            // 创建属性文本
            let attributeText = NSMutableAttributedString(string: titleText)
            // name: 属性名称
            // value: 属性的值
            // range: 哪些范围添加属性
            // 用户名称添加属性
            let nameRange = (titleText as NSString).range(of: name)
            
            attributeText.addAttributes([NSFontAttributeName : UIFont.systemFont(ofSize: 11), NSForegroundColorAttributeName: UIColor.lightGray], range: nameRange)
            
            // 设置属性文本
            label.attributedText = attributeText
            
            // 设置大小
            label.sizeToFit()
            
            navigationItem.titleView = label
        } else {
            // 没有用户名称,直接显示 发微博
            navigationItem.title = prefix
        }
    }
    
    // MARK: - 按钮点击事件
    func close() -> Void {
        SVProgressHUD.dismiss()
        textView.resignFirstResponder()
        self.dismiss(animated: true, completion: nil)
    }
    
    func sendStatus() -> Void {
        // 获取要发布的内容
        let status = textView.emoticonText()
        
        // 微博长度
        let length = status.characters.count
        
        // 计算文本剩余长度
        let leftLength = statusMaxLength - length
        if leftLength < 0 {
            SVProgressHUD.showError(withStatus: "文字超出长度")
            return
        }
        
        SVProgressHUD.showInfo(withStatus: "正在发布微博")
        
        let image = photoSelectorVC.photos.first
        
        HMStatusListViewModel.shared.sendStatus(status: status, image: image) { (error: Error?) in
            if error != nil {
                SVProgressHUD.showError(withStatus: "发布微博失败")
                print("error \(error)")
                return
            }
            
            // 发布微博成功了
            SVProgressHUD.showSuccess(withStatus: "发布微博成功")
            DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1, execute: {
                self.close()
            })
        }
    }
    
    // MARK: - 懒加载
    lazy var sendButton: UIButton = {
        let button = UIButton()
        
        button.setTitleColor(UIColor.black, for: UIControlState.normal)
        button.setTitle("发布", for: UIControlState.normal)
        button.setBackgroundImage(UIImage(named: "common_button_orange"), for: UIControlState.normal)
        button.setBackgroundImage(UIImage(named: "common_button_orange_highlighted"), for: UIControlState.highlighted)
        button.setBackgroundImage(UIImage(named: "common_button_white_disable"), for: UIControlState.disabled)
        
        button.frame = CGRect(x: 0, y: 0, width: 45, height: 35)
        button.addTarget(self, action: #selector(sendStatus), for: UIControlEvents.touchUpInside)
        
        return button
    }()
    
    /// 自定义表情键盘
    private lazy var emoticonKeyboard: HMEmoticonKeyboard = {
        let keyboard = HMEmoticonKeyboard.emoticonKeyboard()
        
        keyboard.textView = self.textView
        
        return keyboard
    }()
    
    /// 照片选择器
    private lazy var photoSelectorVC: HMPhotoSelectorViewController = HMPhotoSelectorViewController()
}

extension HMComposeViewController: UITextViewDelegate {
    func textViewDidChange(_ textView: UITextView) {
        sendButton.isEnabled = textView.hasText
        
        // 计算剩余文本的长度
        let text = textView.emoticonText()
        
        let length = statusMaxLength - text.characters.count
        
        // 设置文本内容
        lengthTipLabel.text = "\(length)"
        
        // 设置文本颜色, length < 0 红色
        lengthTipLabel.textColor = length < 0 ? UIColor.red : UIColor.lightGray
    }
}
